<template>
  <view class="detail-page">
    <Navbar title="监测设备明细" />

    <!-- 设备信息头部 -->
    <view class="device-header">
      <image
        class="device-status"
        src="/static/img/homePages/device-status.png"
        mode="widthFix"
      ></image>
      <view class="device-info">
        <view class="info-row">
          <text class="info-label">设备号</text>
          <text class="info-value">{{ deviceInfo.number }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">所在位置</text>
          <view class="info-value device-location">
            <text 
              class="location-text"
              @longpress="showLocationModal"
            >
              {{ deviceInfo.location }}
            </text>
          </view>
        </view>
        <view class="info-row">
          <text class="info-label">设备状态</text>
          <text class="info-value status-working">{{ deviceInfo.status }}</text>
        </view>
      </view>
    </view>

    <!-- 用电趋势图 -->
    <view class="chart-section">
      <view class="chart-title">
        <view class="title-text">用电趋势图</view>
      </view>
      <view class="chart-container-box">
        <view class="chart-header">
          <view class="step">功率（W）</view>
          <view class="chart-controls">
            <view
              class="control-btn"
              :class="{ active: isPowerToday }"
              @click="selectPowerToday"
              >今日</view>
            <view
              class="control-btn"
              :class="{ active: !isPowerToday }"
              @click="showPowerCalendar = true"
              >{{ isPowerToday ? '历史查询' : powerDate || '历史查询' }}</view>
          </view>
        </view>
        <view class="current-value">
          <view v-if="selectedIndexPower !== null">
            {{ isPowerToday ? '今日' : powerDate }} {{ selectedXPower }}时 <text class="highlight-value">{{ selectedYPower }}W</text>
          </view>
          <view v-else></view>
        </view>
        <view class="chart-container">
          <qiun-data-charts
            type="area"
            :opts="powerOpts"
            :chartData="powerChartData"
            :animation="false"
            @getIndex="onPowerChartPointClick"
          />
        </view>
      </view>
      <tn-popup
        v-model="showPowerCalendar"
        open-direction="bottom"
        :custom-style="{ borderRadius: '32rpx 32rpx 0 0' }"
      >
        <tn-calendar
          v-model="powerDate"
          active-bg-color="#1ec8e1"
          active-text-color="#fff"
          min-date="2025-01-01"
          :max-date="maxDate"
          class="console-calendar"
          @change="onPowerDateChange"
        />
      </tn-popup>
    </view>

    <!-- 电流趋势图 -->
    <view class="chart-section">
      <view class="chart-title">
        <view class="title-text">电流趋势图</view>
      </view>
      <view class="chart-container-box">
        <view class="chart-header">
          <view class="step">电流（A）</view>
          <view class="chart-controls">
            <view
              class="control-btn"
              :class="{ active: isCurrentToday }"
              @click="selectCurrentToday"
              >今日</view>
            <view
              class="control-btn"
              :class="{ active: !isCurrentToday }"
              @click="showCurrentCalendar = true"
              >{{ isCurrentToday ? '历史查询' : currentDate || '历史查询' }}</view>
          </view>
        </view>
        <view class="current-value">
          <view v-if="selectedIndex !== null">
            {{ isCurrentToday ? '今日' : currentDate }} {{ selectedX }}时 <text class="highlight-value">{{ selectedY }}A</text>
          </view>
          <view v-else></view>
        </view>
        <view class="chart-container">
          <qiun-data-charts
            type="area"
            :opts="currentOpts"
            :chartData="currentChartData"
            :animation="false"
            @getIndex="onChartPointClick"
          />
        </view>
      </view>
      <tn-popup
        v-model="showCurrentCalendar"
        open-direction="bottom"
        :custom-style="{ borderRadius: '32rpx 32rpx 0 0' }"
      >
        <tn-calendar
          v-model="currentDate"
          active-bg-color="#1ec8e1"
          active-text-color="#fff"
          min-date="2025-01-01"
          :max-date="maxDate"
          class="console-calendar"
          @change="onCurrentDateChange"
        />
      </tn-popup>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, nextTick, watch } from 'vue';
import Navbar from '@/components/Navbar.vue';
import { createRequest } from '@/utils/request';
import { onLoad, onUnload } from '@dcloudio/uni-app';

function getTodayStr() {
  const today = new Date();
  return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(
    2,
    '0'
  )}-${String(today.getDate()).padStart(2, '0')}`;
}

// 用电趋势图
const powerDate = ref(getTodayStr());
const showPowerCalendar = ref(false);
const isPowerToday = computed(() => powerDate.value === getTodayStr());
function selectPowerToday() {
  powerDate.value = getTodayStr();
  fetchPowerChartData();
}



// 电流趋势图
const currentDate = ref(getTodayStr());
const showCurrentCalendar = ref(false);
const isCurrentToday = computed(() => currentDate.value === getTodayStr());
function selectCurrentToday() {
  currentDate.value = getTodayStr();
  fetchCurrentChartData();
}



function getPowerValueText() {
  return isPowerToday.value ? '今日9:00产生' : `${powerDate.value} 9:00产生`;
}

function getCurrentValueText() {
  return isCurrentToday.value
    ? '今日9:00产生'
    : `${currentDate.value} 9:00产生`;
}

// 功率日期变化事件处理（保留用于模板中的 @change 事件）
function onPowerDateChange(value) {
  // 日期格式转换已在 watch 中处理
}

// 电流日期变化事件处理（保留用于模板中的 @change 事件）
function onCurrentDateChange(value) {
  // 日期格式转换已在 watch 中处理
}

const selectedIndex = ref(null);
const selectedX = ref(null);
const selectedY = ref(null);

function onChartPointClick(e) {
  if (e?.currentIndex?.index != null) {
    const idx = e.currentIndex.index;
    selectedIndex.value = idx;
    selectedX.value = currentChartData.value.categories[idx];
    selectedY.value = currentChartData.value.series[0].data[idx];
  }
}

const selectedIndexPower = ref(null);
const selectedXPower = ref(null);
const selectedYPower = ref(null);

function onPowerChartPointClick(e) {
  if (e?.currentIndex?.index != null) {
    const idx = e.currentIndex.index;
    selectedIndexPower.value = idx;
    selectedXPower.value = powerChartData.value.categories[idx];
    selectedYPower.value = powerChartData.value.series[0].data[idx];
  }
}

const device = ref(null);

// 安全访问设备信息的计算属性
const deviceInfo = computed(() => {
  return device.value || {};
});

// 显示位置弹窗
const showLocationModal = () => {
  if (device.value?.location) {
    uni.showToast({
      title: device.value.location,
      icon: 'none',
      duration: 4000
    });
  }
};

const maxDate = computed(getTodayStr);

// 用电趋势图数据
const powerChartData = ref({
  categories: [
    '1',
    '3',
    '5',
    '7',
    '9',
    '11',
    '13',
    '15',
    '17',
    '19',
    '21',
    '23',
  ],
  series: [
    {
      name: '功率',
      data: [200, 350, 280, 450, 790, 680, 520, 480, 600, 750, 820, 650],
      color: '#1ec8e1',
    },
  ],
});

const powerOpts = ref({
  color: ['#1ec8e1'],
  enableScroll: false,
  width: 330,
  dataLabel: false,
  dataPointShape: false,
  legend: { show: false },
  xAxis: {
    disableGrid: true,
    fontColor: 'rgba(255, 255, 255, 0.2)',
    fontSize: 12,
    rotateLabel: false,
    itemCount: 12,
    boundaryGap: 'center',
    labelCount: 30,
    margin: 10,
  },
  yAxis: {
    gridType: 'solid',
    showTitle: false,
    gridColor: 'rgba(255, 255, 255, 0.2)',
    data: [{ title: '功率(W)', min: 0, max: 1200 }],
    fontColor: 'rgba(255, 255, 255, 0.2)',
    fontSize: 12,
  },
  extra: {
    area: {
      type: 'curve',
      width: 2,
      opacity: 0.2,
      activeType: 'none',
    },
  },
});

// 电流趋势图数据
const currentChartData = ref({
  categories: [
    '1',
    '3',
    '5',
    '7',
    '9',
    '11',
    '13',
    '15',
    '17',
    '19',
    '21',
    '23',
  ],
  series: [
    {
      name: '电流',
      data: [5, 8, 6, 12, 16, 14, 10, 9, 11, 15, 18, 13],
      color: '#1ec8e1',
    },
  ],
});
const currentOpts = ref({
  color: ['#1ec8e1'],
  enableScroll: false,
  width: 330,
  dataLabel: false,
  dataPointShape: false,
  legend: { show: false },
  xAxis: {
    disableGrid: true,
    fontColor: 'rgba(255, 255, 255, 0.2)',
    fontSize: 12,
    rotateLabel: false,
    itemCount: 12,
    boundaryGap: 'center',
    labelCount: 30,
    margin: 10,
  },
  yAxis: {
    gridType: 'solid',
    showTitle: false,
    gridColor: 'rgba(255, 255, 255, 0.2)',
    data: [{ title: '电流(A)', min: 0, max: 30 }],
    fontColor: 'rgba(255, 255, 255, 0.2)',
    fontSize: 12,
  },
  extra: {
    area: {
      type: 'curve',
      width: 2,
      opacity: 0.2,
      activeType: 'none',
      pointShape: 'none', // 兼容性写法
      pointShow: false    // 兼容性写法
    },
  },
});

// 获取设备详情
async function fetchDeviceDetail(options) {
  // 从页面参数中获取设备信息
  const { id, deviceCode, location, number, value } = options;
  
  // 解码URL编码的参数
  const decodedLocation = location ? decodeURIComponent(location) : '';
  const decodedNumber = number ? decodeURIComponent(number) : '';
  const decodedDeviceCode = deviceCode ? decodeURIComponent(deviceCode) : '';
  const decodedValue = value ? decodeURIComponent(value) : '';
  
  // 如果有传递的设备信息，直接使用
  if (decodedDeviceCode && decodedLocation && decodedNumber) {
    // 根据value判断状态
    const status = decodedValue === 'true' ? '工作中' : '未工作';
    // 在location后面拼接number
    const fullLocation = `${decodedLocation}${decodedNumber}`;
    
    device.value = {
      id: id,
      deviceCode: decodedDeviceCode,
      number: decodedNumber,
      location: fullLocation,
      status: status,
    };
    
    // 初始化位置文本状态
    // 无需特殊初始化
  }
}

// 用电趋势图数据
async function fetchPowerChartData() {
  // 构建请求参数
  const startTime = encodeURIComponent(powerDate.value + 'T00:00:00');
  const endTime = encodeURIComponent(powerDate.value + 'T23:59:59');
  
  try {
    // 发送请求获取功率数据
    const response = await createRequest(`/monitor/${device.value.id}/power?startTime=${startTime}&endTime=${endTime}`);
    
    if (response.code === 200 && response.data) {
      const dataValues = Object.values(response.data);
      
      // 如果数据超过12条，截取前12条
      const limitedData = dataValues.slice(0, 12);
      
      powerChartData.value = {
        categories: [
          '1',
          '3',
          '5',
          '7',
          '9',
          '11',
          '13',
          '15',
          '17',
          '19',
          '21',
          '23',
        ],
        series: [{ name: '功率', data: limitedData, color: '#1ec8e1' }],
      };
    } else {
      console.warn('功率API响应异常:', response);
    }
  } catch (error) {
    console.error('功率数据请求失败:', error);
  }
  
  updateChartRanges();
}

// 电流趋势图数据
async function fetchCurrentChartData() {
  // 构建请求参数
  const startTime = encodeURIComponent(currentDate.value + 'T00:00:00');
  const endTime = encodeURIComponent(currentDate.value + 'T23:59:59');
  
  try {
    // 发送请求获取电流数据
    const response = await createRequest(`/monitor/${device.value.id}/current?startTime=${startTime}&endTime=${endTime}`);
    
    if (response.code === 200 && response.data) {
      const dataValues = Object.values(response.data);
      
      // 如果数据超过12条，截取前12条
      const limitedData = dataValues.slice(0, 12);
      
      currentChartData.value = {
        categories: [
          '1',
          '3',
          '5',
          '7',
          '9',
          '11',
          '13',
          '15',
          '17',
          '19',
          '21',
          '23',
        ],
        series: [{ name: '电流', data: limitedData, color: '#1ec8e1' }],
      };
    } else {
      console.warn('电流API响应异常:', response);
    }
  } catch (error) {
    console.error('电流数据请求失败:', error);
  }
  
  updateChartRanges();
}

function updateChartRanges() {
  // 更新功率图表Y轴范围
  const powerData = powerChartData.value.series[0].data;
  const powerMax = Math.max(...powerData);
  const newPowerMax = Math.ceil(powerMax / 200) * 200;
  powerOpts.value.yAxis.data[0].max = newPowerMax;
  
  // 更新电流图表Y轴范围
  const currentData = currentChartData.value.series[0].data;
  const currentMax = Math.max(...currentData);
  const newCurrentMax = Math.ceil(currentMax / 5) * 5;
  currentOpts.value.yAxis.data[0].max = newCurrentMax;
}

onLoad(async options => {
  fetchDeviceDetail(options);
  
  // 页面加载完成后，等待下一个tick再获取数据
  // 确保 deviceInfo 已经设置完成
  nextTick(() => {
    // 延迟一点时间确保参数完全设置完成
    setTimeout(() => {
      if (device.value?.id) {
        fetchPowerChartData();
        fetchCurrentChartData();
      }
    }, 100);
  });
});

// 监听日期变化，自动刷新数据
watch(powerDate, newDate => {
  // 转换日期格式：YYYY/MM/DD -> YYYY-MM-DD
  if (newDate && newDate.includes('/')) {
    const formattedDate = newDate.replace(/\//g, '-');
    powerDate.value = formattedDate;
  }

  // 日期变化时，延迟一点时间再检查日历状态
  setTimeout(() => {
    if (!showPowerCalendar.value) {
      fetchPowerChartData();
    }
  }, 100);
});

watch(currentDate, newDate => {
  // 转换日期格式：YYYY/MM/DD -> YYYY-MM-DD
  if (newDate && newDate.includes('/')) {
    const formattedDate = newDate.replace(/\//g, '-');
    currentDate.value = formattedDate;
  }

  // 日期变化时，延迟一点时间再检查日历状态
  setTimeout(() => {
    if (!showCurrentCalendar.value) {
      fetchCurrentChartData();
    }
  }, 100);
});

// 监听日历选择器关闭事件
watch(showPowerCalendar, (newVal, oldVal) => {
  // 当日历从打开变为关闭时，如果日期已变化则刷新数据
  if (oldVal && !newVal) {
    fetchPowerChartData();
  }
});

watch(showCurrentCalendar, (newVal, oldVal) => {
  // 当日历从打开变为关闭时，如果日期已变化则刷新数据
  if (oldVal && !newVal) {
    fetchCurrentChartData();
  }
});

// 页面卸载时清理状态
onUnload(() => {
  // 无需特殊清理
});
</script>

<style scoped lang="scss">
.detail-page {
  @include page-with-header;
  background: #172869;
  min-height: 100vh;
}

.device-header {
  width: 686rpx;
  height: 240rpx;
  margin: 32rpx auto 40rpx;
  background-image: url('/static/img/homePages/device-header.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  padding: 40rpx 30rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.device-status {
  width: 116rpx;
  height: 160rpx;
}

.device-info {
  width: 470rpx;
  height: 148rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}

.info-row {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.info-label {
  color: rgba(255, 255, 255, 0.6);
  font-size: 28rpx;
}

.info-value {
  color: rgba(255, 255, 255, 0.8);
  font-size: 28rpx;
  font-weight: 500;
}

.status-working {
  color: #04dee1 !important;
}

.device-location {
  max-width: 280rpx;
  overflow: hidden;
}

.location-text {
  color: rgba(255, 255, 255, 0.8);
  font-size: 28rpx;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: block;
}

.chart-section {
  margin: 0 auto 40rpx;
  width: 686rpx;
}

.chart-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 66rpx;
  padding: 30rpx 30rpx 0;
  box-sizing: border-box;
}
.step{
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.9);
}
.chart-title {
  width: 686rpx;
  height: 68rpx;
  background-image: url('/static/img/homePages/chart-title.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  position: relative;
}

.title-text {
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  font-style: italic;
  position: absolute;
  left: 60rpx;
  top: 8rpx;
}
.chart-container-box {
  width: 686rpx;
  height: 554rpx;
  background-image: url('/static/img/homePages/chart-container-box.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
}
.chart-controls{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  min-width: 260rpx;
}
.control-btn {
  padding: 4rpx 24rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.6);
  background: rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;

  &.active {
    background: rgba(255, 255, 255, 0.1);
    color: #0978EC;
  }
}

.current-value {
  width: 610rpx;
  height: 40rpx;
  margin: 26rpx auto 10rpx;
  background-color: rgba(255, 255, 255, 0.1);
  padding: 4rpx 8rpx;
  box-sizing: border-box;
  text-align: center;
  line-height: 40rpx;
  color: rgba(255, 255, 255, 0.9);
  font-size: 24rpx;
}

.highlight-value {
  color: #1ec8e1;
}

.chart-container {
  height: 370rpx;
  width: 660rpx;
  margin: 0 auto;
}

// 日期选择器样式
.date-picker-container {
  background: #fff;
  border-radius: 32rpx 32rpx 0 0;
  overflow: hidden;
}

.date-picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.date-picker-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.date-picker-actions {
  display: flex;
  gap: 20rpx;
}

.action-btn {
  font-size: 28rpx;
  color: #666;
  padding: 8rpx 16rpx;

  &.confirm {
    color: #1ec8e1;
    font-weight: 500;
  }
}

.console-calendar {
  // padding: 0 60rpx 60rpx 0;
  box-sizing: border-box;
  color: #eee;
  // 你可以继续添加更多自定义样式
}

:deep(.uni-picker-view-mask) {
  background: transparent !important;
}

// 清空calendar数据区域的padding
:deep(.tn-calendar__data) {
  box-sizing: border-box !important;
}

// 清空calendar星期文字的padding
:deep(.tn-calendar__week-text) {
  box-sizing: border-box !important;
}

:deep(.tn-calendar__operation) {
  box-sizing: border-box !important;
}
</style>
